import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserId, setUserId, removeUserId } from '@/utils/user-id'
import { login as loginApi, getUserInfo as getUserInfoApi } from '@/api/user'

const state = {
  token: getToken(), // 从本地缓存中获取
  userId: getUserId(),
  userInfo: {}
}
const mutations = {
  updateToken(state, token) {
    state.token = token
    // 存入本地
    setToken(token)
  },
  removeToken() {
    state.token = null
    removeToken()
  },
  updateUserInfo(state, payload) {
    state.userInfo = payload
  },
  setUserId(state, userId) {
    state.userId = userId
    setUserId(userId)
  },
  updateUserId(state, userId) {
    state.userId = userId
    // 存入本地
    setUserId(userId)
  },
  removeUserId() {
    state.userId = null
    removeUserId()
  }
}

const actions = {
  async login({ commit }, data) {
    // 在这个函数里去调用登录的接口
    const res = await loginApi(data)
    console.log(res)
    commit('updateToken', res.token) // 调用mutations里的函数，将token存到本地和仓库
    commit('updateUserId', res.userId)
  },
  async getUserInfo(context) {
    const res = await getUserInfoApi(context.state.userId)
    // console.log(res)
    context.commit('updateUserInfo', res)
  },
  logout({ commit }) {
    commit('removeToken')
    commit('updateUserInfo', {})
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
